package com.cup.ali.sms.vcode;

import java.util.Map;
import java.util.Observer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;


/**
 * 验证码定时器:有效120s
 */
public class VcodeTimer extends java.util.Observable {
	/** 
     * 验证码失效线程池：默认分配3个线程处理
     */  
    public static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(3);  
    
	private static Logger logger = Logger.getLogger(VcodeTimer.class);
	/**
	 * 计时器:通知验证码失效
	 * @param value
	 */
	private void number(Object value,Integer second) {
		setChanged();
		notifyObservers(value);
	}
	
	/**
	 * 登记观察者，根据观察者要求添加任务计划
	 * @param map
	 */
	public void add(Observer ob,Map<String,Object> map,Integer second){
		
		TimerTask task = new TimerTask(){
			public void run(){
				/*观察者*/  
		        addObserver(ob); 
		        number(map,second);  
			}
		};
		
		if(threadPool == null){
			threadPool = Executors.newScheduledThreadPool(3);  
		}
		//任务计划
		threadPool.schedule(task, second, TimeUnit.SECONDS);
		
		logger.info("scheduled:"+JSON.toJSONString(map));
		
	}
}
